package cc.bluemc.modules.adminUser.action;

import cc.bluemc.modules.adminUser.entity.Permission;
import cc.bluemc.modules.adminUser.entity.Role;
import cc.bluemc.modules.adminUser.service.PermissionService;
import cc.bluemc.modules.adminUser.service.RoleService;
import cc.bluemc.platform.comm.ActionResultMap;
import cc.bluemc.platform.comm.BaseAction;
import cc.bluemc.platform.jdbctemplatetool.exception.NoColumnAnnotationFoundException;
import cc.bluemc.platform.jdbctemplatetool.exception.NoIdAnnotationFoundException;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/admin/role")
public class RoleAction extends BaseAction{
	@Autowired
	private RoleService roleService;
	@Autowired
	private PermissionService permissionService;
	
	@RequestMapping("form")
	public String addForm(Integer id,Model model) throws NoIdAnnotationFoundException, NoColumnAnnotationFoundException{
		if(null!=id){
			Role role= roleService.getBean(id);
			model.addAttribute("bean", role);
		}
		return "adminUser/roleForm";
	}
	@RequestMapping("save")
	public String save(Role role,Model model){
		try {
			if(null==role.getId()){
				roleService.save(role);
			}else{
				roleService.updateBean(role);
			}
			resultMap.setSuccess(true);
			
		} catch (Exception e) {
			resultMap.setSuccess(false);
			resultMap.setMsg("保存失败");
		}
		return "redirect:list";
	}
	@RequestMapping("list")
	public String list(Model model){
		resultMap.setSuccess(true);
		List<Role> list = roleService.getAllRoles();
		resultMap.setData(list);
		model.addAttribute(_RESULTMAP,resultMap);
		return "adminUser/roleList";
	}
	@RequestMapping("ajax/setPermiForm")
	public String setPermiForm(Integer id,Model model) throws NoIdAnnotationFoundException, NoColumnAnnotationFoundException{
		//roleId
		model.addAttribute("roleId", id);
		//所有功能权限
		List<Permission> permiss = permissionService.getAll(id);
		model.addAttribute("permissionTree",JSON.toJSONString(permiss));
		
		return "adminUser/roleSetPermi";
	}
	@ResponseBody
	@RequestMapping("setPermi")
	public ActionResultMap setPermi(Integer roleId,@RequestParam(value="permis[]",required=false)Integer [] permis){
		resultMap.setSuccess(true);
		roleService.setPermi(roleId,permis);
		resultMap.setMsg("权限设置成功");
		return resultMap;	
	}
}
